package com.zz.spring6.jdbc;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

import java.util.List;

@SpringJUnitConfig(locations = "classpath:bean.xml")
public class JdbcTemplateTest {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //  查 返回对象
    @Test
    public void testSelectObject(){
        // 1
//        String sql ="select * from t_emp where id =?";
//        Emp empResult = jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {
//            Emp emp = new Emp();
//            emp.setId(rs.getInt("id"));
//            emp.setName(rs.getString("name"));
//            emp.setAge(rs.getInt("age"));
//            emp.setSex(rs.getString("sex"));
//            return emp;
//        }, 1);
//        System.out.println(empResult);

        // 2
        String sql ="select * from t_emp where id =?";
        Emp emp = jdbcTemplate.queryForObject(sql,
                new BeanPropertyRowMapper<>(Emp.class),1);
        System.out.println(emp);
    }

    // 查 返回list集合
    @Test
    public void testSelectList(){
        String sql ="select * from t_emp";
        List<Emp> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Emp.class));
        System.out.println(list);
    }
    // 查 返回单个值
    @Test
    public void testSelectValue(){
        String sql ="select count(*) from t_emp";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        System.out.println(count);
    }


    @Test
    public void testUpdate(){
        // 1 添加
//        String sql ="insert into t_emp values(null,?,?,?)";
//        Object[] params= {"林平之", 20, "未知"};
//        int rows = jdbcTemplate.update(sql, params);
//        System.out.println(rows);

        //2 修改
//        String sql ="update t_emp set name =? where id =?";
//        Object[] params= {"林平之zzz", 3};
//        int rows = jdbcTemplate.update(sql, params);
//        System.out.println(rows);


        //3 删除操作
        String sql ="delete from t_emp where id =?";
        int rows = jdbcTemplate.update(sql, 3);
        System.out.println(rows);

    }

}
